using Microsoft.Extensions.Logging;
using TaskScheduler.Core;
using TaskScheduler.Infrastructure.Services;

namespace TaskScheduler.Tasks;

/// <summary>
/// 周报任务示例 - 展示如何使用自定义服务
/// 这个任务展示了如何在任务中注入和使用多个服务
/// </summary>
public class WeeklyReportTask : ITask
{
    private readonly ILogger<WeeklyReportTask> _logger;
    private readonly IEmailService _emailService;
    private readonly IFeishuService _feishuService;

    // 构造函数注入需要的服务
    public WeeklyReportTask(
        ILogger<WeeklyReportTask> logger,
        IEmailService emailService,
        IFeishuService feishuService)
    {
        _logger = logger;
        _emailService = emailService;
        _feishuService = feishuService;
    }

    public string TaskName => "WeeklyReportTask";
    public string Description => "每周报告任务 - 展示服务使用示例";
    public bool IsEnabled => true;
    public string CronExpression => "0 9 * * 1"; // 每周一早上9点执行

    public async Task<TaskResult> ExecuteAsync(CancellationToken cancellationToken = default)
    {
        try
        {
            _logger.LogInformation("开始生成周报...");

            // 1. 收集本周数据
            var weeklyData = await CollectWeeklyDataAsync(cancellationToken);
            _logger.LogInformation("收集到本周数据: {Count} 项", weeklyData.Count);

            // 2. 生成报告内容
            var reportContent = GenerateWeeklyReport(weeklyData);

            // 3. 使用邮件服务发送报告
            var emailSent = await _emailService.SendEmailAsync(
                "manager@example.com",
                $"周报 - {DateTime.Now:yyyy-MM-dd}",
                reportContent
            );

            // 4. 使用飞书服务发送通知
            var feishuSent = await _feishuService.SendMessageAsync(
                "📊 本周数据报告",
                reportContent
            );

            // 5. 返回执行结果
            var success = emailSent && feishuSent;
            return new TaskResult
            {
                IsSuccess = success,
                Message = success 
                    ? "周报生成并发送成功" 
                    : "周报发送部分失败，请查看日志"
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "生成周报失败");
            return new TaskResult
            {
                IsSuccess = false,
                Message = ex.Message,
                Exception = ex
            };
        }
    }

    /// <summary>
    /// 收集本周数据（示例）
    /// </summary>
    private async Task<Dictionary<string, object>> CollectWeeklyDataAsync(CancellationToken cancellationToken)
    {
        await Task.Delay(200, cancellationToken);

        // 这里是示例数据，实际使用时应该从数据库或其他数据源获取
        var startOfWeek = DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek + 1);
        var endOfWeek = startOfWeek.AddDays(7);

        return new Dictionary<string, object>
        {
            ["周期"] = $"{startOfWeek:yyyy-MM-dd} 至 {endOfWeek:yyyy-MM-dd}",
            ["新增用户"] = 156,
            ["活跃用户"] = 2340,
            ["订单总数"] = 892,
            ["营收金额"] = 45678.90m,
            ["用户满意度"] = "95.5%"
        };
    }

    /// <summary>
    /// 生成周报内容
    /// </summary>
    private string GenerateWeeklyReport(Dictionary<string, object> data)
    {
        var lines = new List<string>
        {
            "📊 本周数据汇总",
            new string('=', 40),
            ""
        };

        foreach (var (key, value) in data)
        {
            lines.Add($"{key}: {value}");
        }

        lines.Add("");
        lines.Add("---");
        lines.Add($"生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");

        return string.Join("\n", lines);
    }
}

